from bot.enterprise_wechat_gpt.util.tair_util import *


def monitor_timeout(processing_timeout, front_handle_time):
    if processing_timeout >= 0:
        tair_util.hincr("QW:ServerMonitor", "total_processing_timeout", processing_timeout)
        tair_util.hincr("QW:ServerMonitor", "TotalCount", 1)

        total_count = tair_util.hget("QW:ServerMonitor", "TotalCount")
        if int(total_count) % 10 == 9:
            total_processing_timeout = tair_util.hget('QW:ServerMonitor', 'total_processing_timeout')
            average = int(total_processing_timeout) / int(total_count)
            tair_util.hset("QW:ServerMonitor", "average_processing_timeout", average)
            if average > 30:
                logging.warning(f"[报警] 最近10次平均延迟处理时间超过30s:{average/60}m")
            tair_util.hset("QW:ServerMonitor", "total_processing_timeout", 0)
            tair_util.hset("QW:ServerMonitor", "TotalCount", 0)

    if front_handle_time > 0:
        tair_util.hincr("QW:ServerMonitor", "total_front_handle_time", front_handle_time)
        tair_util.hincr("QW:ServerMonitor", "TotalFrontCount", 1)

        total_count = tair_util.hget("QW:ServerMonitor", "TotalFrontCount")
        if int(total_count) % 20 == 19:
            total_front_handle_time = tair_util.hget('QW:ServerMonitor', 'total_front_handle_time')
            average = int(total_front_handle_time) / int(total_count)
            tair_util.hset("QW:ServerMonitor", "average_front_handle_time", average)
            if average > 300:
                logging.warning(f"[报警] 最近20次平均前端处理时间超过五分钟:{average/60}m")
            tair_util.hset("QW:ServerMonitor", "total_front_handle_time", 0)
            tair_util.hset("QW:ServerMonitor", "TotalFrontCount", 0)


if __name__ == '__main__':
    import random
    for i in range(100):
        print(i)
        # 获取60到70之间的随机数
        monitor_timeout(random.randint(1, 20), random.randint(300, 400))
